import AsyncStorage from "@react-native-async-storage/async-storage";

class UserManager {
  private static instance: UserManager;
  private _userInfo: any = null;

  private constructor() {} // Make constructor private to prevent direct instantiation

  static getInstance() {
    if (!UserManager.instance) {
      UserManager.instance = new UserManager();
    }
    return UserManager.instance;
  }

  // 设置用户信息并保护数据
  async setUserInfo(userInfo: string) {
    try {
      await AsyncStorage.setItem("userInfo", userInfo);
      this._userInfo = JSON.parse(userInfo);
    } catch (error) {
      console.error("Error setting user info:", error);
    }
  }

  // 获取用户信息
  async getUserInfo() {
    try {
      const userInfo = await AsyncStorage.getItem("userInfo");
      this._userInfo = JSON.parse(userInfo || "{}");
      return this._userInfo;
    } catch (error) {
      console.error("Error getting user info:", error);
      return null;
    }
  }

  // 检查是否已登录
  async isLoggedIn() {
    const userInfo = await this.getUserInfo();
    return userInfo !== null;
  }

  // 清除用户信息（登出）
  async clearUserInfo() {
    try {
      await AsyncStorage.removeItem("userInfo");
      this._userInfo = null;
    } catch (error) {
      console.error("Error clearing user info:", error);
    }
  }

  get UserInfo() {
    return this._userInfo;
  }
}

const userManager = UserManager.getInstance();

export default userManager;
